﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;

/// <summary>
/// VerifyCode 的摘要说明
/// </summary>
public class VerifyCodeHelper
{
    //创建验证码
    public static string GenerateCheckCode()
    {
        int number;
        char code;
        string CheckCode = string.Empty;
        System.Random random = new Random();
        for (int i = 0; i < 4; i++)
        {
            number = random.Next();
            if (number % 2 == 0)
                code = (char)('0' + (char)(number % 10));
            else
                code = (char)('a' + (char)(number % 26));
            CheckCode += code.ToString();
        }
        return CheckCode;
    }

    //产生验证码背景图像
    public static MemoryStream CreateVerifyCode(string checkCode)
    {
        if (checkCode == null || checkCode.Trim() == string.Empty)
            return null;
        System.Drawing.Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 19.0)), 38);
        Graphics g = Graphics.FromImage(image);
        try
        {
            //生成随机生成器
            Random random = new Random();
            //清空图片背景色
            g.Clear(Color.White);
            Font font = new Font("Verdana", 17, (FontStyle.Bold | FontStyle.Italic));
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.FromArgb(133, 133, 133), Color.FromArgb(133, 133, 133), 1.2f, true);
            g.DrawString(checkCode, font, brush, 2, 2);
            //画图片的边框线
            MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            return ms;
        }
        finally
        {
            g.Dispose();
            image.Dispose();
        }
    }
}